package com.framework.admin.controller;

import com.wf.captcha.base.Captcha;
import com.framework.admin.domain.param.AuthUserParam;
import com.framework.admin.domain.vo.ImgCode;
import com.framework.admin.service.ILoginService;
import com.framework.admin.service.IUserService;
import com.framework.common.constant.ErrorCode;
import com.framework.common.domain.LoginCode;
import com.framework.common.domain.ResultData;
import com.framework.common.em.LoginCodeEnum;
import com.framework.common.exception.BusinessException;
import com.framework.common.model.UserInfo;
import com.framework.common.util.CaptchaUtil;
import com.framework.common.util.RSAEncrypt;
import com.framework.common.util.RedisUtil;
import com.framework.oauthclient.util.OauthClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.UUID;

@Controller
@CrossOrigin(origins = "*", maxAge = 3600)  //跨域请求
@RequestMapping( "/login")
@Api(value = "login", tags = "系统登录")
public class LoginController {
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    IUserService userService;
    @Autowired
    ILoginService loginService;
    @Autowired
    OauthClient oauthClient;
    @Value("${login.privateKey}")
    String privateKey;

    @ApiOperation("登录授权")
    @PostMapping(value = "/login")
    @ResponseBody
    public ResultData login(@Validated @RequestBody AuthUserParam authUser) throws Exception {
        // 查询验证码
        String code = redisUtil.get(authUser.getUuid());
        // 清除验证码
        redisUtil.del(authUser.getUuid());
        if (StringUtils.isBlank(code)) {
            throw new BusinessException(ErrorCode.Login.vilidateCodeTimeout);
        }
        if (StringUtils.isBlank(authUser.getCode()) || !authUser.getCode().equalsIgnoreCase(code)) {
            throw new BusinessException(ErrorCode.Login.errorVilidateCode);
        }

        // RSA 解密
        authUser.setPassword(RSAEncrypt.decrypt(authUser.getPassword(), privateKey));
        // 返回 token 与 用户信息
        Map<String, Object> authInfo = loginService.doLogin(authUser.getUsername(), authUser.getPassword());
        return ResultData.data(authInfo);
    }

    /**
     * 获取登录验证码
     */
    @ResponseBody
    @ApiOperation(value = "获取登录验证码")
    @GetMapping(value = "/code")
    public ImgCode list() {
        String uuid = UUID.randomUUID().toString();
        LoginCode code = new LoginCode();
        code.setCodeType(LoginCodeEnum.arithmetic);
        CaptchaUtil util = new CaptchaUtil();
        Captcha captcha = util.switchCaptcha(code);
        ImgCode imgCode = new ImgCode();
        imgCode.setImg(captcha.toBase64());
        imgCode.setUuid(uuid);
        // 120秒过期
        redisUtil.set(uuid, util.result(captcha), 120L);
        return imgCode;
    }

    @ResponseBody
    @ApiOperation("登录授权")
    @GetMapping(value = "/info")
    public ResultData<UserInfo> info(@RequestParam boolean cache, HttpServletRequest request) {
        UserInfo userInfo;
        String token = request.getHeader("Authorization");
        token = token.substring(7);
        if (cache) {
            userInfo = redisUtil.get(token);
        } else {
            userInfo = oauthClient.userInfo(token);
        }

        return ResultData.data(userInfo);
    }

    @ResponseBody
    @ApiOperation("退出登录")
    @RequestMapping(value = "/logout", method = RequestMethod.DELETE)
    public ResultData<String> loginOut(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        redisUtil.del(token);
        return ResultData.success();
    }

}